<template>
  <el-dialog
    custom-class="collection-back-payment"
    v-el-drag-dialog="{ drag: true, full: false, resize: false }"
    title="收款-平账操作"
    :close-on-click-modal="false"
    :visible="true"
    @close="closeMd"
    width="90%"
    append-to-body>
    <div class="paid-wrapper">
      <div class="item itemTitle c-red">订单多收列表</div>
      <div class="item">合计多收金额：<b class="c-red">{{ dg.totalOverchargeMoney }}元</b></div>
      <div class="item">订单数：{{ dg.overChargeList.length }}单</div>
    </div>
    <el-form 
      :model="fm.ps" 
      :ref="fm.fname">
      <el-table 
        :data="dg.overChargeList"
        row-key="id"
        :height="fullHeight/2 - 150"
        border fit
        @select="selRow">
        <el-table-column 
          fixed="left" 
          type="index" 
          label="编号" 
          width="40" 
          align="center" 
          :resizable="false">
        </el-table-column>

        <el-table-column label="行程详情" prop="routeDetail" width="auto">
          <template slot-scope="{row}">
            <div v-for="(o, i) in row.routeDetail" :key="i">{{(row.routeDetail.length > 1 ? (i+1)+'、' : '')+o}}</div>
          </template>
        </el-table-column>

        <el-table-column label="订单价格" prop="price" width="80"></el-table-column>
        <el-table-column label="已收金额" prop="alGathPrice" width="80"></el-table-column>

        <el-table-column label="多收金额" prop="overchargeMoney" width="80">
          <template slot-scope="{row}">
            <div>-{{row.overchargeMoney}}</div>
          </template>
        </el-table-column>

        <el-table-column label="本次平账金额" prop="currBalanceAccountMoney" width="100">
          <template slot-scope="{row}">
            <div>{{row.balanceAccountsMoney}}</div>
          </template>
        </el-table-column>

        <el-table-column label="平账后结差" prop="balanceAccountDiffMoney" width="100">
          <template slot-scope="{row}">
            <div>{{row.balanceAccountsDiff}}</div>
          </template>
        </el-table-column>

        <el-table-column label="客户" prop="customId" width="150">
          <template slot-scope="{row}">
            <div>{{row.carOrderBase.customId.unitName}}</div>
          </template>
        </el-table-column>

        <el-table-column label="财务备注" prop="operNote" width="350">
          <template slot-scope="{row}">
            <el-form-item
              v-if="fm.ps.operNoteArr.length > 0"
              :prop="`operNoteArr.${row.index - 1}.operNote`"
              :rules="[{ required: true, message: '财务备注不能为空', trigger: 'blur' }]">
              <el-input
                clearable
                style="width: 100%"
                placeholder="请填写财务备注"
                v-model="fm.ps.operNoteArr[row.index - 1].operNote">
              </el-input>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="130">
          <template slot-scope="{$index}">
            <el-button 
              size="mini"
              type="primary" 
              icon="el-icon-bottom"
              title="向下单条填充财务备注"
              @click.native="downFill($index, 1, 1)">
              向下单条填充
            </el-button>
            <div style="padding: 5px;"></div>
            <el-button 
              size="mini"
              type="primary" 
              icon="el-icon-bottom"
              title="向下全部填充财务备注"
              @click.native="downFill($index, 1, 0)">
              向下全部填充
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="computed-money-wrapper">
        <div class="item"><b>合计</b></div>
        <div class="item">已选订单: {{ dg.overChargeList.length }} + {{ dg.receivableList.length }}</div>
        <div class="item">多收金额: <b class="c-red">{{ dg.totalOverchargeMoney }}元</b></div>
        <div class="item">应收金额: <b class="c-green">{{ dg.totalReceivableMoney }}元</b></div>
        <div class="item">可平账金额: {{ dg.totalBalanceAccountsMoney }}元</div>
        <div class="item">平账结差: {{ dg.totalBalanceAccountsDiff }}元</div>
        <div class="item">
          <el-button 
            :loading="sb.load" 
            style="margin-left: 20px" 
            type="primary" 
            icon="el-icon-s-order"
            @click="okBalanceAccount">
            {{sb.text}}
          </el-button>
        </div>
      </div>

      <div class="paid-wrapper">
        <div class="item itemTitle c-green">订单应收列表</div>
        <div class="item">合计应收金额：<b class="c-green">{{ dg.totalReceivableMoney }}</b>元</div>
        <div class="item">订单数：{{ dg.receivableList.length }}单</div>
      </div>
      <el-table 
        :data="dg.receivableList"
        row-key="id"
        :height="fullHeight/2 - 150"
        border fit
        @select="selRow">
        <el-table-column 
          fixed="left" 
          type="index" 
          label="编号" 
          width="40" 
          align="center" 
          :resizable="false">
        </el-table-column>

        <el-table-column label="行程详情" prop="routeDetail" width="auto">
          <template slot-scope="{row}">
            <div v-for="(o, i) in row.routeDetail" :key="i">{{(row.routeDetail.length > 1 ? (i+1)+'、' : '')+o}}</div>
          </template>
        </el-table-column>

        <el-table-column label="订单价格" prop="price" width="80"></el-table-column>
        <el-table-column label="已收金额" prop="alGathPrice" width="80"></el-table-column>
        <el-table-column label="应收金额" prop="receivableMoney" width="80">
          <template slot-scope="{row}">
            <div>{{row.receivableMoney}}</div>
          </template>
        </el-table-column>

        <el-table-column label="本次平账金额" prop="currBalanceAccountMoney" width="100">
          <template slot-scope="{row}">
            <div>{{row.balanceAccountsMoney}}</div>
          </template>
        </el-table-column>

        <el-table-column label="平账后结差" prop="balanceAccountDiffMoney" width="100">
          <template slot-scope="{row}">
            <div>{{row.balanceAccountsDiff}}</div>
          </template>
        </el-table-column>

        <el-table-column label="客户" prop="customId" width="150">
          <template slot-scope="{row}">
            <div>{{row.carOrderBase.customId.unitName}}</div>
          </template>
        </el-table-column>

        <el-table-column label="财务备注" prop="operNote" width="350">
          <template slot-scope="{row}">
            <el-form-item
              v-if="fm.ps.operNoteArr.length > 0"
              :prop="`operNoteArr.${row.index - 1}.operNote`"
              :rules="[{ required: true, message: '财务备注不能为空', trigger: 'blur' }]">
              <el-input
                clearable
                style="width: 100%"
                placeholder="请填写财务备注"
                v-model="fm.ps.operNoteArr[row.index - 1].operNote">
              </el-input>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="130">
          <template slot-scope="{$index}">
            <el-button 
              size="mini"
              type="primary" 
              icon="el-icon-bottom"
              title="向下单条填充财务备注"
              @click.native="downFill($index, 2, 1)">
              向下单条填充
            </el-button>
            <div style="padding: 5px;"></div>
            <el-button 
              size="mini"
              type="primary" 
              icon="el-icon-bottom"
              title="向下全部填充财务备注"
              @click.native="downFill($index, 2, 0)">
              向下全部填充
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

  </el-dialog>
</template>

<script>
import {mapGetters} from "vuex";
import elDragDialog from "@/directive/el-drag-dialog";
import * as orderSer from "@/api/services/order.service";

export default {
  name: "CollectionBackPayment",
  directives: {elDragDialog},
  props: {myData: Object},
  computed: {
    ...mapGetters(["lunitNum", "uname"])
  },
  data() {
    return {
      // 屏幕高度
      fullHeight: this.U.fullHeight(),
      // 提交按钮
      sb: {
        load: false,
        text: "确认平账",
      },
      dg: {
        // 多收列表
        overChargeList: [],   
        // 多收总金额
        totalOverchargeMoney: 0,
        // 应收列表
        receivableList: [],   
        // 应收总金额
        totalReceivableMoney: 0,  
        // 可平账总金额
        totalBalanceAccountsMoney: 0,  
        // 平账结差
        totalBalanceAccountsDiff: 0,
      },
      fm: {
        fname: 'balanceAccoutnsFm',
        ps: {
          // 财务备注
          operNoteArr: [],
        },
      },
    };
  },
  created() {
    // console.log('父组件传入数据：', this.myData);
    const that = this, { data } = that.myData;
    
    if (data && data.length > 0) {
      // 初始化财务备注项
      data.forEach((it, i) => {
        it.index = i+1;
        that.fm.ps.operNoteArr.push({id: it.id, operNote: ''});
      });
      
      // 多收列表
      that.dg.overChargeList = data.filter(it => it.price - it.alGathPrice < 0);
      // 多收总金额 = 每单已收 - 每天价格
      let sum1 = 0;
      that.dg.overChargeList.forEach(it => { sum1 += it.alGathPrice - it.price; });
      that.dg.totalOverchargeMoney = sum1;


      // 应收列表
      that.dg.receivableList = data.filter(it => it.price - it.alGathPrice >= 0);
      // 应收总金额 = 每单价格 - 每单已收
      let sum2 = 0;
      that.dg.receivableList.forEach(it => { sum2 += it.price; });
      that.dg.totalReceivableMoney = sum2;
      
      // 可平账金额（多收与应收取其小金额）
      if(that.dg.totalOverchargeMoney > that.dg.totalReceivableMoney){
        that.dg.totalBalanceAccountsMoney = that.dg.totalReceivableMoney;
      }else{
        that.dg.totalBalanceAccountsMoney = that.dg.totalOverchargeMoney;
      }

      // 平账结差（多收与应收，大金额-小金额）
      if(that.dg.totalOverchargeMoney > that.dg.totalReceivableMoney){
        that.dg.totalBalanceAccountsDiff = that.dg.totalOverchargeMoney - that.dg.totalReceivableMoney;
      }else{
        that.dg.totalBalanceAccountsDiff = that.dg.totalReceivableMoney - that.dg.totalOverchargeMoney;
      }


      // 多收列表
      let tempTotalReceivableMoney = that.dg.totalReceivableMoney;
      that.dg.overChargeList.forEach(it => {
        // 每单多收金额 = 每单已收金额 - 每单订单金额
        it.overchargeMoney = (it.alGathPrice - it.price).toFixed(2);

        // 【多收 小于 应收】 多收平完
        if(that.dg.totalOverchargeMoney <= that.dg.totalReceivableMoney){
          // 平账金额 = 多收金额，即平完
          it.balanceAccountsMoney = it.overchargeMoney;
          // 平账后结差 = 0
          it.balanceAccountsDiff = 0;
        }else{// 【多收 大于 应收】 多收每个订单用应收总金额去循环平账（依次减）
          // 总应收金额 < 当前单多收金额
          if(tempTotalReceivableMoney < it.overchargeMoney){
            // 平账金额 = 总应收金额，即未平完（当前单多收金额有剩余）
            it.balanceAccountsMoney = tempTotalReceivableMoney;
            // 平账后结差 = 当前订单多收金额 - 总应收金额
            it.balanceAccountsDiff = it.overchargeMoney - tempTotalReceivableMoney;

            // 剩余总应收金额为0
            tempTotalReceivableMoney = 0;
          }else{
            // 平账金额 = 多收金额，即当前单已平完
            it.balanceAccountsMoney = it.overchargeMoney;
            // 平账后结差 = 0
            it.balanceAccountsDiff = 0;

            // 剩余总应收金额
            tempTotalReceivableMoney -= it.overchargeMoney;
            // 剩余总应收金额最小为0
            if(tempTotalReceivableMoney <= 0) tempTotalReceivableMoney = 0;
          }
        }
      });

      // 应收列表
      let tempTotalOverchargeMoney = that.dg.totalOverchargeMoney;
      that.dg.receivableList.forEach(it => {
        // 每单应收金额 = 每单订单金额 - 每单已收金额
        it.receivableMoney = (it.price - it.alGathPrice).toFixed(2);

        // 【应收 小于 多收】 应收平完
        if(that.dg.totalReceivableMoney <= that.dg.totalOverchargeMoney){
          // 平账金额 = 应收金额，即平完
          it.balanceAccountsMoney = it.receivableMoney;
          // 平账后结差 = 0
          it.balanceAccountsDiff = 0;
        }else{// 【应收 大于 多收】 应收每个订单用多收总金额去循环平账（依次减）
          // 总多收金额 < 当前单应收金额
          if(tempTotalOverchargeMoney < it.receivableMoney){
            // 平账金额 = 总多收金额，即未平完（当前单应收金额有剩余）
            it.balanceAccountsMoney = tempTotalOverchargeMoney;
            // 平账后结差 = 当前单应收金额 - 总多收金额
            it.balanceAccountsDiff = it.receivableMoney - tempTotalOverchargeMoney;

            // 剩余总多收金额为0
            tempTotalOverchargeMoney = 0;
          }else{
            // 平账金额 = 应收金额，即当前订单已平完
            it.balanceAccountsMoney = it.receivableMoney;
            // 平账后结差 = 0
            it.balanceAccountsDiff = 0;

            // 剩余总多收金额
            tempTotalOverchargeMoney -= it.receivableMoney;
            // 剩余总多收金额最小为0
            if(tempTotalOverchargeMoney <= 0) tempTotalOverchargeMoney = 0;
          }
        }
      });

      console.log('多收列表', that.dg.overChargeList);
      console.log('应收列表', that.dg.receivableList);

    }
  },

  methods: {
    closeMd() {
      this.$emit("myClick", {state: false});
    },
    // 选择列表行数据
    selRow(rows, row) {
      console.log('选择的行', rows);
    },
    /**
     * 向下填充-财务备注
     * @param {Object} $index 当前行的下标
     * @param {number} type 1-订单多收列表 2-订单应收列表
     * @param {number} count 向下填充数量0-全部 大于0表示几条
     */
    downFill($index, type, count){
      let that = this, U = that.U, { operNoteArr } = that.fm.ps;
      
      let list = type == 1 ? that.dg.overChargeList : that.dg.receivableList;

      let curOperNoteIndex = operNoteArr.findIndex(it => it.id == list[$index].id);
      if(operNoteArr[curOperNoteIndex] && !operNoteArr[curOperNoteIndex].operNote) {
        that.$refs[that.fm.fname].validateField(`operNoteArr.${curOperNoteIndex}.operNote`);
      }else{
        let c = 0;
        for(let i = 0; i < list.length; i++){
          if(count != 0 && c == count) break;

          if(i > $index){
            let is = operNoteArr.findIndex(it => it.id == list[i].id);
            if(is != -1) {
              operNoteArr[is].operNote = operNoteArr[curOperNoteIndex].operNote;
              c++;
            }
          }
        }
      }
    },
    // 确认平账
    okBalanceAccount() {
      const that = this, {overChargeList, receivableList} = that.dg, {operNoteArr} = that.fm.ps, sb = that.sb;
      
      that.$refs[that.fm.fname].validate((valid) => {
        if (!valid) { return false; }else {

          let noMp = {};
          operNoteArr.forEach(it => {noMp[it.id+''] = it.operNote;});

          let ps = {
            moreGathOrder: overChargeList.map(item => ({orderId: item.id, moreMoney: item.balanceAccountsMoney, remark: noMp[item.id+'']})),
            shouldGathOrder: receivableList.map(item => ({orderId: item.id, gathMoney: item.balanceAccountsMoney, remark: noMp[item.id+'']}))
          }

          console.log('提交参数', ps);
          sb.load = true;
          orderSer.setGathDebt(ps).then(res => {
            sb.load = false;

            if (res.code !== 1) {
              return that.U.qerror(res.msg);
            }
            that.closeMd();
            that.$emit("reloadDg");
          });

        }
      });
    }

  },
};
</script>
<style lang="less" scoped>
.paid-wrapper {
  display: flex;
  padding: 10px 0;
  border: 1px solid #ddd;
  border-bottom: none;
  .item {
    margin-right: 20px;
    padding: 0 10px;
    &.itemTitle {
      width: 150px;
      font-weight: bold;
      color: #203a65;
      margin-right: 10px;
    }
  }
}

.computed-money-wrapper {
  margin: 10px 0;
  display: flex;
  align-items: center;
  padding: 10px;
  border: 1px solid #ddd;
  background: #f3f3f3;
  .item {
    margin-right: 16px;
  }
}
</style>